package com.promise.jokerdream.ui.customtask

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.ui.draw.clip
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.ui.res.painterResource
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import androidx.compose.ui.platform.LocalContext
import com.promise.jokerdream.database.UserDataManager
import com.promise.jokerdream.R
import com.promise.jokerdream.navigation.AppRoute
import com.promise.jokerdream.ui.components.DangerAlertDialog
import com.promise.jokerdream.ui.components.TaskNameInputDialog
import com.promise.jokerdream.ui.theme.AppFontSizes
import com.promise.jokerdream.ui.theme.AppSpacing
import com.promise.jokerdream.ui.theme.AppColors
import com.promise.jokerdream.ui.toolbar.AppTopBar
import com.promise.jokerdream.database.entity.TaskGroupConfigEntity

/**
 * 自定义任务页面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CustomTaskPage(
    userId: String,
    onBackClick: () -> Unit,
    onNavigateToExecutionLog: () -> Unit,
    navController: NavHostController? = null
) {
    var showTaskNameDialog by remember { mutableStateOf(false) }
    val context = LocalContext.current
    val userDataManager = remember { UserDataManager.getInstance(context) }
    
    // 从UserConfig加载任务组列表
    var taskGroupList by remember { 
        mutableStateOf<List<TaskGroupConfigEntity>>(emptyList()) 
    }
    
    // 任务数量映射表（groupId -> count）
    var taskCountMap by remember { 
        mutableStateOf<Map<Long, Int>>(emptyMap()) 
    }
    
    // 滑动删除状态
    var swipedTaskGroupId by remember { mutableStateOf<Long?>(null) }
    var showDeleteDialog by remember { mutableStateOf(false) }
    var taskGroupToDelete by remember { mutableStateOf<TaskGroupConfigEntity?>(null) }
    
    // 加载任务组列表和任务数量
    LaunchedEffect(userId) {
        val account = userDataManager.getUserAccount(userId)
        taskGroupList = account?.config?.taskListConfig ?: emptyList()
        
        // 查询每个任务组的任务数量
        val countMap = taskGroupList.associate { group ->
            group.groupId to userDataManager.getTaskCountByGroupId(group.groupId)
        }
        taskCountMap = countMap
    }
    
    // 处理返回键
    BackHandler {
        onBackClick()
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.background)
    ) {
        // 顶部导航栏
        AppTopBar(
            title = "自定义任务",
            onBackClick = onBackClick,
            actionIcon = {
                Button(
                    onClick = { showTaskNameDialog = true },
                    modifier = Modifier.height(28.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary
                    ),
                    contentPadding = PaddingValues(horizontal = AppSpacing.componentLarge)
                ) {
                    Text(
                        text = "新建",
                        fontSize = AppFontSizes.buttonMedium,
                        color = MaterialTheme.colorScheme.onPrimary
                    )
                }
            }
        )
        
        // 内容区域
        if (taskGroupList.isEmpty()) {
            // 空状态
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(AppSpacing.pageHorizontal),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Text(
                    text = "暂无任务组",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Medium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                Text(
                    text = "点击右上角\"新建\"按钮创建任务组",
                    fontSize = 14.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    textAlign = TextAlign.Center
                )
            }
        } else {
            // 任务组列表
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = AppSpacing.pageHorizontal),
                verticalArrangement = Arrangement.spacedBy(12.dp),
                contentPadding = PaddingValues(vertical = AppSpacing.pageVertical)
            ) {
                items(taskGroupList) { taskGroup ->
                    SwipeableTaskGroupItem(
                        taskGroup = taskGroup,
                        taskCount = taskCountMap[taskGroup.groupId] ?: 0,
                        isSwiped = swipedTaskGroupId == taskGroup.groupId,
                        onClick = {
                            navController?.navigate(AppRoute.TaskConfig.route.replace("{taskGroupId}", taskGroup.groupId.toString()))
                        },
                        onSwipeStart = { swipedTaskGroupId = taskGroup.groupId },
                        onSwipeEnd = { swipedTaskGroupId = null },
                        onDelete = {
                            taskGroupToDelete = taskGroup
                            showDeleteDialog = true
                        }
                    )
                }
            }
        }
    }
    
    // 任务名称输入对话框
    TaskNameInputDialog(
        show = showTaskNameDialog,
        onTaskNameEntered = { taskName ->
            showTaskNameDialog = false
            // 创建新的任务组
            val newTaskGroup = TaskGroupConfigEntity(
                userId = userId,
                groupName = taskName
            )
            // 保存任务组
            userDataManager.insertTaskGroup(userId, newTaskGroup)
            // 重新加载获取数据库生成的 groupId
            val savedAccount = userDataManager.getUserAccount(userId)
            val savedGroup = savedAccount?.config?.taskListConfig?.findLast { it.groupName == taskName }
            taskGroupList = savedAccount?.config?.taskListConfig ?: emptyList()
            // 跳转到任务配置页面，使用数据库生成的 groupId
            savedGroup?.let { group ->
                navController?.navigate(AppRoute.TaskConfig.route.replace("{taskGroupId}", group.groupId.toString()))
            }
        },
        onDismiss = { showTaskNameDialog = false }
    )
    
    // 删除确认对话框
    DangerAlertDialog(
        show = showDeleteDialog,
        title = "删除任务组",
        content = "确定要删除任务组 \"${taskGroupToDelete?.groupName}\" ？",
        confirmText = "删除",
        cancelText = "取消",
        onDismiss = { 
            showDeleteDialog = false
            taskGroupToDelete = null
        },
        onConfirm = {
            taskGroupToDelete?.let { taskGroup ->
                // 删除任务组（会级联删除所有关联的任务）
                userDataManager.deleteTaskGroup(taskGroup.groupId)
                
                // 重新加载任务组列表
                val account = userDataManager.getUserAccount(userId)
                taskGroupList = account?.config?.taskListConfig ?: emptyList()
                
                showDeleteDialog = false
                taskGroupToDelete = null
                swipedTaskGroupId = null
            }
        }
    )
}

/**
 * 可滑动的任务组Item
 */
@Composable
private fun SwipeableTaskGroupItem(
    taskGroup: TaskGroupConfigEntity,
    taskCount: Int,
    isSwiped: Boolean,
    onClick: () -> Unit,
    onSwipeStart: () -> Unit,
    onSwipeEnd: () -> Unit,
    onDelete: () -> Unit,
    modifier: Modifier = Modifier
) {
    var offsetX by remember { mutableStateOf(0f) }
    val swipeThreshold = 80f
    
    // 当其他任务组项开始滑动时，重置当前项的滑动状态
    LaunchedEffect(isSwiped) {
        if (!isSwiped) {
            offsetX = 0f
        }
    }
    
    Box(
        modifier = modifier
            .fillMaxWidth()
            .height(80.dp) // 增加高度以容纳内容
    ) {
        // 删除按钮背景 - 跟随手势左滑拉出
        if (offsetX < 0) {
            Box(
                modifier = Modifier
                    .fillMaxHeight()
                    .width((-offsetX).dp)
                    .background(Color.Red)
                    .align(Alignment.CenterEnd)
            ) {
                IconButton(
                    onClick = { onDelete() },
                    modifier = Modifier.align(Alignment.Center)
                ) {
                    Icon(
                        painter = painterResource(id = R.drawable.ic_delete),
                        contentDescription = "删除任务组",
                        tint = Color.White,
                        modifier = Modifier.size(24.dp)
                    )
                }
            }
        }
        
        // 任务组项
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight()
                .offset(x = offsetX.dp)
                .background(
                    color = MaterialTheme.colorScheme.surface,
                    shape = RoundedCornerShape(12.dp)
                )
                .pointerInput(Unit) {
                    detectHorizontalDragGestures(
                        onDragStart = { onSwipeStart() },
                        onDragEnd = {
                            if (offsetX < -swipeThreshold/2) {
                                offsetX = -swipeThreshold
                            } else {
                                offsetX = 0f
                                onSwipeEnd()
                            }
                        }
                    ) { _, x ->
                        if (x < 0) {
                            offsetX = (offsetX + x).coerceAtLeast(-swipeThreshold)
                        } else if (offsetX < 0) {
                            offsetX = (offsetX + x).coerceAtMost(0f)
                        }
                    }
                }
                .clickable { 
                    if (offsetX == 0f) {
                        onClick()
                    }
                }
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .fillMaxHeight()
                    .padding(12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column(
                    modifier = Modifier.weight(1f)
                ) {
                    Text(
                        text = taskGroup.groupName,
                        fontSize = AppFontSizes.body,
                        fontWeight = FontWeight.Medium,
                        color = AppColors.TextPrimary,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis
                    )
                    
                    Spacer(modifier = Modifier.height(6.dp))
                    
                    Text(
                        text = "任务数量：$taskCount",
                        fontSize = AppFontSizes.mediumBody,
                        color = AppColors.TextSecondary
                    )
                }
            }
        }
    }
}
